////
////  FistTestingManager.m
////  安好
////
////  Created by qinlongqing on 14/12/8.
////  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
////
//
//#import "FistTestingManager.h"
//#import <CoreMotion/CoreMotion.h>
//#import "AppConfig.h"
//
//static FistTestingManager *instance = nil;
//
//@interface FistTestingManager ()
//{
//    CMMotionManager *motionManager;
//    
//    NSMutableArray *accelerometerArray;//存储每一时刻的速度大小
//    
//    NSTimer *limitTimer;//10s限制
//    NSInteger timerCount;//统计执行的秒数
//    
//    BOOL isRising;//标记当前是上升还是下降
//    NSMutableArray *countArray;//所有被筛选出来的数据
//    
//    CGFloat kMinAcceleration;//标记过滤最小值
//}
//@end
//
//@implementation FistTestingManager
//
//+ (FistTestingManager *)instance{
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        instance = [[self alloc] init];
//    });
//    return instance;
//}
//
//- (void)start{
//    isRising = YES;//默认上升
//    
//    if (!countArray) {
//        countArray = [[NSMutableArray alloc]init];
//    }
//    [countArray removeAllObjects];
//    
//    timerCount = 0;
//    limitTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(doTimerCount) userInfo:nil repeats:YES];
//    
//    accelerometerArray = [[NSMutableArray alloc]initWithCapacity:0];
//    
//    motionManager = [[CMMotionManager alloc]init];
//    motionManager.accelerometerUpdateInterval = 0.08f;
//    [motionManager startAccelerometerUpdatesToQueue:[[NSOperationQueue alloc]init] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
//        double x_2 = pow(accelerometerData.acceleration.x, 2);
//        double y_2 = pow(accelerometerData.acceleration.y, 2);
//        double z_2 = pow(accelerometerData.acceleration.z, 2);
//        double vectorSum = sqrt(x_2 + y_2 + z_2);//开平方
//        
//        [accelerometerArray addObject:[NSNumber numberWithDouble:vectorSum]];
//        
//    }];
//}
//
//- (void)doTimerCount{
//    timerCount +=1;
//    if (timerCount == 10) {
//        [limitTimer invalidate];
//        limitTimer = nil;
//        
//        [motionManager stopAccelerometerUpdates];
//        
//        [self countAccelerometerData];
//        
////        [self writeToFile];
//        
//        [accelerometerArray removeAllObjects];
//        
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if (self.delegate && [self.delegate respondsToSelector:@selector(loadTestResult:)]) {
//                [self.delegate loadTestResult:[NSDictionary dictionaryWithObjectsAndKeys:countArray,kHuiQuanTestDataArray, nil]];
//            }
//        });
//    }
//    else{
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if (self.delegate && [self.delegate respondsToSelector:@selector(doTimerCount:)]) {
//                [self.delegate doTimerCount:timerCount];
//            }
//        });
//    }
//}
//
//- (void)countAccelerometerData{
//    if (accelerometerArray.count > 0) {
//        if (kScreenHeight == 480) {
//            kMinAcceleration = 2.5;
//        }
//        else if (kScreenHeight == 568){
//            kMinAcceleration = 7.0;
//        }
//        for (NSInteger i=0; i<(accelerometerArray.count - 1); i++) {
//            double firstNumber = [[accelerometerArray objectAtIndex:i] doubleValue];
//            double secondNumber = [[accelerometerArray objectAtIndex:(i+1)] doubleValue];
//            if (firstNumber > secondNumber) {
//                if (isRising == YES) {
//                    if (firstNumber > kMinAcceleration) {
//                        [countArray addObject:[NSNumber numberWithDouble:firstNumber]];
//                    }
//                }
//                isRising = NO;
//            }
//            else{
//                if (i == (accelerometerArray.count - 2)) {
//                    if (secondNumber > kMinAcceleration) {
//                        [countArray addObject:[NSNumber numberWithDouble:secondNumber]];
//                    }
//                }
//                isRising = YES;
//            }
//        }
//    }
//}
//
//- (void)writeToFile{
//    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0] stringByAppendingPathComponent:@"acc.plist"];
//    NSFileManager *fm = [NSFileManager defaultManager];
//    if ([fm fileExistsAtPath:filePath]) {
//        [fm removeItemAtPath:filePath error:nil];
//    }
//    [accelerometerArray writeToFile:filePath atomically:NO];
//}
//
//
//- (void)stop{
//    [limitTimer invalidate];
//    limitTimer = nil;
//    
//    [motionManager stopAccelerometerUpdates];
//    
//    [accelerometerArray removeAllObjects];
//}
//
//@end


//
//  FistTestingManager.m
//  安好
//
//  Created by qinlongqing on 14/12/8.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "FistTestingManager.h"
#import <CoreMotion/CoreMotion.h>
#import "AppConfig.h"
#import <AVFoundation/AVFoundation.h>
#import "JSMessageSoundEffect.h"

static FistTestingManager *instance = nil;

@interface FistTestingManager ()
{
    CMMotionManager *motionManager;
    
    NSMutableArray *accelerometerArray;//存储每一时刻的速度大小
    
    NSTimer *limitTimer;//10s限制
    NSInteger timerCount;//统计执行的秒数
    
    BOOL isRising;//标记当前是上升还是下降
    double numberBefore;//上次的测试结果
    
    CGFloat kMinAcceleration;//标记过滤最小值
    
    AVAudioPlayer *player;
    
//    NSMutableArray *allAccArray;
}
@end

@implementation FistTestingManager

+ (FistTestingManager *)instance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (void)start{
//    allAccArray = [[NSMutableArray alloc]init];
    
    if (kScreenHeight == 480) {
        kMinAcceleration = 2.5;
    }
    else{
        kMinAcceleration = 7.0;
    }
    
    numberBefore = 0;
    
    isRising = YES;//默认上升
    
    timerCount = 0;
    limitTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(doTimerCount) userInfo:nil repeats:YES];
    
    accelerometerArray = [[NSMutableArray alloc]initWithCapacity:0];
    
    motionManager = [[CMMotionManager alloc]init];
    motionManager.accelerometerUpdateInterval = 0.08f;
    [motionManager startAccelerometerUpdatesToQueue:[[NSOperationQueue alloc]init] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
        double x_2 = pow(accelerometerData.acceleration.x, 2);
        double y_2 = pow(accelerometerData.acceleration.y, 2);
        double z_2 = pow(accelerometerData.acceleration.z, 2);
        double vectorSum = sqrt(x_2 + y_2 + z_2);//开平方
        
//        [allAccArray addObject:[NSNumber numberWithDouble:numberBefore]];
        
        if (numberBefore > vectorSum) {
            if (isRising == YES) {
                if (numberBefore > kMinAcceleration) {
                    [accelerometerArray addObject:[NSNumber numberWithDouble:numberBefore]];
                    
                    [self playOneFist];//播放挥拳一次音乐
                }
            }
            isRising = NO;
        }
        else{
            if (isRising == NO) {
                if (numberBefore > kMinAcceleration) {
                    [accelerometerArray addObject:[NSNumber numberWithDouble:numberBefore]];
                }
            }
            isRising = YES;
        }
        
        numberBefore = vectorSum;
    }];
}

- (void)doTimerCount{
    timerCount +=1;
    if (timerCount == 10) {
        [limitTimer invalidate];
        limitTimer = nil;
        
        [motionManager stopAccelerometerUpdates];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.delegate && [self.delegate respondsToSelector:@selector(loadTestResult:)]) {
                [self.delegate loadTestResult:[NSDictionary dictionaryWithObjectsAndKeys:accelerometerArray,kHuiQuanTestDataArray, nil]];
            }
            [accelerometerArray removeAllObjects];
        });
        
//        [self writeAllAccToLocal];
    }
    else{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.delegate && [self.delegate respondsToSelector:@selector(doTimerCount:)]) {
                [self.delegate doTimerCount:timerCount];
            }
        });
    }
}

- (void)stop{
    [limitTimer invalidate];
    limitTimer = nil;
    
    [motionManager stopAccelerometerUpdates];
    
    [accelerometerArray removeAllObjects];
}

- (void)playOneFist{
//    NSString *fileName = [[NSBundle mainBundle] pathForResource:@"一次挥拳" ofType:@"mp3"];
//    [JSMessageSoundEffect playSoundWithName:fileName type:@"mp3"];

    NSString *fileName = [[NSBundle mainBundle] pathForResource:@"一次挥拳" ofType:@"mp3"];
    NSURL *fileUrl = [NSURL fileURLWithPath:fileName];
    NSError *error = nil;
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:&error];
    [player setNumberOfLoops:0]; //默认为0，即播放一次就结束；如果设置为负值，则音频内容会不停的循环播放下去。
    [player prepareToPlay];
    [player play];
}


//- (void)writeAllAccToLocal{
//    NSString *path =  [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"acc.xml"];
//    
//    NSFileManager *fm = [NSFileManager defaultManager];
//    if ([fm fileExistsAtPath:path]) {
//        [fm removeItemAtPath:path error:nil];
//    }
//    [allAccArray writeToFile:path atomically:NO];
//
//}

@end

